/*
	版权所有 2009-2024 荆门泽优软件有限公司 保留所有版权。
    版本：1.0
    更新记录：
        2024-03-07 创建
*/
function zyOfficeManager()
{
    //url=>res/
    //http://localhost:8888/zyoffice/js/w.js=>
    this.getJsDir = function () {
        var js = document.scripts;
        var jsPath;
        for (var i = 0; i < js.length; i++) {
            if (js[i].src.indexOf("zyOffice/") > -1) {
                jsPath = js[i].src.substring(0, js[i].src.indexOf("zyOffice/"));
            }
        }
        return jsPath;
    };
    var rootDir = this.getJsDir()+"zyOffice/";
    //http://localhost/WordPaster/css/
    var pathRes = rootDir + "css/";

    var _this = this;
    //导入word
    UE.registerUI('importword', function (editor, uiName) {
        editor.registerCommand(uiName, {
            execCommand: function () {
                editor.focus();
                _this.SetEditor(editor);
                _this.api.openDoc();
            }
        });
        var iconUrl = pathRes + 'w.png';

        var btn = new UE.ui.Button({
            name: "导入Word文档（docx格式）",
            //提示
            title: '导入Word文档（docx格式）',            
            onclick: function () {
                editor.focus();
                _this.SetEditor(editor);
                _this.api.openDoc();
            },
            getHtmlTpl: function () {
                return (
                    '<div id="##" class="edui-box %%">' +
                    '<div id="##_state" stateful>' +
                    '<div class="%%-wrap"><div id="##_body" unselectable="on" ' +
                    (this.title ? 'title="' + this.title + '"' : "") +
                    ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
                    ('<div class="edui-box edui-icon"><svg t="1735786130164" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1326" width="16" height="16"><path d="M262.498 1024a73.05 73.05 0 0 1-73.018-72.655v-48.942h58.322v48.711a14.861 14.861 0 0 0 14.663 14.531h671.988a14.828 14.828 0 0 0 14.663-14.53V329.62c0-4.426-0.561-33.025-1.585-38.441H715.367V59.808a78.4 78.4 0 0 0-14.597-1.585H262.663A14.828 14.828 0 0 0 248 72.753v146.928h-58.421V72.655A73.084 73.084 0 0 1 262.564 0h438.14a203.697 203.697 0 0 1 124.635 51.486l130.415 130.15a272.256 272.256 0 0 1 51.618 148.05v621.428a73.05 73.05 0 0 1-73.018 72.655z m325.954-212.779H16.628V279.258h571.824V811.22zM304.868 531.237l45.31 173.578h71.103l60.964-312.513h-71.268L382.84 536.554l-32.662-144.252H268.74l-48.744 166.676-32.497-166.676h-71.135l60.964 312.513h71.102l56.44-173.611zM661.536 738.07V671.56h246.035v66.512z m0-132.99V538.6h246.035v66.48z m0-113.044v-66.48h246.035v66.513z" fill="#0081CC" p-id="1327"></path></svg></div>') +
                    "</div>" +
                    "</div>" +
                    "</div></div>"
                );
            }
        });
        editor.addListener('selectionchange', function () {
            var state = editor.queryCommandState(uiName);
            if (state == -1) {
                btn.setDisabled(true);
                btn.setChecked(false);
            } else {
                btn.setDisabled(false);
                btn.setChecked(state);
            }
        });
        editor.addListener('ready', function () {
            _this.SetEditor(editor);
        });
        editor.addListener("firstBeforeExecCommand", function () {
            _this.SetEditor(editor);
        });
        return btn;
    });

    //导出word
    UE.registerUI('exportword', function (editor, uiName) {
        editor.registerCommand(uiName, {
            execCommand: function () {
                editor.focus();
                _this.SetEditor(editor);
                _this.api.exportWord();
            }
        });
        var iconUrl = pathRes + 'exword.png';

        var btn = new UE.ui.Button({
            name: "导出Word文档（docx格式）",
            //提示
            title: '导出Word文档（docx格式）',            
            onclick: function () {
                editor.focus();
                _this.SetEditor(editor);
                _this.api.exportWord();
            },
            getHtmlTpl: function () {
                return (
                    '<div id="##" class="edui-box %%">' +
                    '<div id="##_state" stateful>' +
                    '<div class="%%-wrap"><div id="##_body" unselectable="on" ' +
                    (this.title ? 'title="' + this.title + '"' : "") +
                    ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
                    ('<div class="edui-box edui-icon"><svg t="1735786163626" class="icon" viewBox="0 0 1034 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1592" width="16" height="16"><path d="M614.4 795.281752h149.489051v103.147445l270.575183-155.468613L763.889051 585.99708v104.642336h-149.489051zM230.213139 70.259854a16.085022 16.085022 0 0 1 14.948905-14.948905h436.508029a56.088292 56.088292 0 0 1 14.948905 1.49489v231.70803h231.708029a351.060088 351.060088 0 0 1 1.494891 38.867153V621.874453l58.30073 35.877372V328.875912c0-40.362044-23.918248-119.591241-50.826278-147.99416L807.240876 50.826277C778.837956 22.423358 723.527007 0 683.164964 0H245.162044a73.369226 73.369226 0 0 0-73.249635 73.249635v146.49927h58.30073z m524.706569 11.959124a64.997839 64.997839 0 0 1 10.464234 8.969343L895.439416 221.243796a64.997839 64.997839 0 0 1 8.969343 10.464233h-149.489051z m0 0" p-id="1593"></path><path d="M614.4 363.258394h239.182482v68.764964h-239.182482zM929.821898 950.750365a16.085022 16.085022 0 0 1-14.948905 14.948905H245.162044a16.085022 16.085022 0 0 1-14.948905-14.948905v-49.331387h-58.30073V950.750365A73.369226 73.369226 0 0 0 245.162044 1024h671.205839A73.369226 73.369226 0 0 0 989.617518 950.750365v-122.581022l-58.30073 34.382482V950.750365z m-382.691971-663.731387H0v547.129927h547.129927z m67.270073 212.274453h239.182482V568.058394h-239.182482z m0 0" p-id="1594"></path><path d="M415.041401 385.681752l-59.915211 216.519941-53.277898-216.519941H241.93308L185.366423 602.201693 132.088526 385.681752H58.898686L152.060263 735.486131h63.263766l56.566657-208.20835L325.168584 735.486131H385.083796l103.147445-349.804379H415.041401z" fill="#FFFFFF" p-id="1595"></path></svg></div>') +
                    "</div>" +
                    "</div>" +
                    "</div></div>"
                );
            }
        });
        editor.addListener('selectionchange', function () {
            var state = editor.queryCommandState(uiName);
            if (state == -1) {
                btn.setDisabled(true);
                btn.setChecked(false);
            } else {
                btn.setDisabled(false);
                btn.setChecked(state);
            }
        });
        editor.addListener('ready', function () {
            _this.SetEditor(editor);
        });
        editor.addListener("firstBeforeExecCommand", function () {
            _this.SetEditor(editor);
        });
        return btn;
    });

    UE.registerUI('importpdf', function (editor, uiName) {
        editor.registerCommand(uiName, {
            execCommand: function () {
                editor.focus();
                _this.SetEditor(editor);
                _this.api.openPdf();
            }
        });
        var iconUrl = pathRes + 'pdf.png';

        var btn = new UE.ui.Button({
            name: "导入PDF文档",
            //提示
            title: '导入PDF文档',            
            onclick: function () {
                editor.focus();
                _this.SetEditor(editor);
                _this.api.openPdf();
            },
            getHtmlTpl: function () {
                return (
                    '<div id="##" class="edui-box %%">' +
                    '<div id="##_state" stateful>' +
                    '<div class="%%-wrap"><div id="##_body" unselectable="on" ' +
                    (this.title ? 'title="' + this.title + '"' : "") +
                    ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
                    ('<div class="edui-box edui-icon"><svg t="1735786235004" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4058" width="16" height="16"><path d="M188.44768 460.8H287.99968c26.4 0 51.712 10.784 70.4 29.984 18.656 19.2 29.152 45.248 29.152 72.416v25.6c0 56.544-44.576 102.4-99.552 102.4H238.20768v102.4H188.47968V460.8z m522.656 204.8v128h-49.76V460.8h174.208V512h-124.448v102.4h99.552v51.2h-99.52zM636.47968 0L959.99968 332.8v588.8a103.744 103.744 0 0 1-29.024 72.352c-18.624 19.2-43.904 30.016-70.272 30.048H163.29568C108.41568 1023.872 63.99968 978.048 63.99968 921.6V102.4C63.99968 45.856 108.51168 0 163.29568 0H636.47968z m-0.512 332.992h253.728l-253.216-260.608-0.512 260.608zM910.20768 384h-273.952c-27.392 0-49.6-22.88-49.6-51.008V51.2H163.29568c-27.264 0-49.504 22.912-49.504 51.2v819.2c0 28.224 22.272 51.2 49.504 51.2h697.408c27.328 0 49.504-22.912 49.504-51.2V384z m-423.104 76.8c68.736 0 124.48 57.28 124.48 128v76.8c0 70.72-55.744 128-124.48 128H412.47968V460.8h74.656z m0 281.6c41.248 0 74.688-34.4 74.688-76.8v-76.8c0-42.4-33.44-76.8-74.688-76.8h-24.896v230.4h24.896zM238.20768 640H287.99968c13.216 0 25.856-5.408 35.2-15.008 9.344-9.6 14.592-22.624 14.592-36.192v-25.6c0-13.568-5.248-26.592-14.592-36.192A49.088 49.088 0 0 0 287.99968 512H238.20768v128z" fill="#3D3D3D" p-id="4059"></path></svg></div>') +
                    "</div>" +
                    "</div>" +
                    "</div></div>"
                );
            }
        });
        editor.addListener('selectionchange', function () {
            var state = editor.queryCommandState(uiName);
            if (state == -1) {
                btn.setDisabled(true);
                btn.setChecked(false);
            } else {
                btn.setDisabled(false);
                btn.setChecked(state);
            }
        });
        editor.addListener('ready', function () {
            _this.SetEditor(editor);
        });
        editor.addListener("firstBeforeExecCommand", function () {
            _this.SetEditor(editor);
        });
        return btn;
    });

    this.event={
        scriptReady: function () {
            $(function () {
                //加载
                if (typeof (_this.ui.render) == "undefined") {
                    _this.LoadTo($(document.body));
                }
                else if (typeof (_this.ui.render) == "string") {
                        _this.LoadTo($("#" + _this.ui.render));
                }
                else if (typeof (_this.ui.render) == "object") {
                    _this.LoadTo(_this.ui.render);
                }
            });
        },
        doc_sel: function (evt) {
            _this.ui.dlg.panel.css("display", "");
            _this.ui.dlg.msg.text("正在转换中");
            _this.api.openDialog();
            var fs = evt.target.files;
            _this.api.upload_doc(fs[0]);
            evt.target.value = null;
        },
        upload_complete: function (evt) {
            var svr = JSON.parse(evt.target.responseText);
            _this.api.insertHtml(svr.body);
            $.skygqbox.hide();
        },
        upload_failed: function () {
            _this.ui.dlg.ico.attr("src", _this.ui.ico.error);
            _this.ui.dlg.msg.text("服务器连接失败，请检查Office文件转换服务是否启动");
        },
        upload_process: function (evt) { }
    };
    this.ui = { editor:null,setup: null ,
        single: null,
        btn: { up: null,exportWord:null,pdf:null },
        dlg: { panel: null, ico: null, msg: null },
        ico:{
            error:pathRes+"error.png",
            upload:pathRes+"upload.gif"
        }
    };
    this.data={
        browser:{name:navigator.userAgent.toLowerCase(),ie:true,ie64:false,chrome:false,firefox:false,edge:false,arm64:false,mips64:false,platform:window.navigator.platform.toLowerCase()},
        error:{
        "0": "连接服务器错误",
        "1": "发送数据错误",
        "2": "接收数据错误"
      },
      type:{local:0/*本地图片*/,network:1/*网络图片*/,word:2/*word图片*/},
      jsCount: 0//已经加载的脚本总数
    };
    this.api = {
        openDoc: function () {
            _this.Config.api=_this.Config.word;
            _this.ui.btn.up.click();
        },
        exportWord:function(){
            var form = new FormData(); // FormData object
            form.append("html", _this.ui.editor.getContent()); // File object

            var req = new XMLHttpRequest();
            req.open("POST", _this.Config.wordExport,true);
            req.responseType = "blob"; // 返回类型blob
            req.onload = function() {
                if (this.status === 200) {
                    var blob = this.response;
                    var reader = new FileReader();
                    reader.readAsDataURL(blob);
                    reader.onload = function(e) {
                        var a = document.createElement('a');
                        a.download = "word-export.docx";
                        a.href = e.target.result;
                        $("body").append(a);
                        a.click();
                        $(a).remove();
                    }
                }
            }
            req.send(form);
        },
        openPdf: function () {
            _this.Config.api=_this.Config.pdf;
            _this.ui.btn.pdf.click();
        },
        openDialog: function () {
            _this.ui.dlg.panel.skygqbox({
                title: "Office文档转换",
                width: "550px",
                height:"160px",
                onclose: function () {
                    _this.ui.dlg.panel.css("display", "none");
                    _this.ui.dlg.ico.attr("src", _this.ui.ico.upload);
                }
            });
        },
        upload_doc: function (file) {
            var fileObj = file;

            var form = new FormData(); // FormData object
            form.append("file", fileObj); // File object

            var xhr = new XMLHttpRequest();  // XMLHttpRequest object
            xhr.open("post", _this.Config.api, true); //post
            xhr.onload = _this.event.upload_complete;
            xhr.onerror = _this.event.upload_failed;

            xhr.upload.onprogress = _this.event.upload_process;
            xhr.upload.onloadstart = function () {
                ot = new Date().getTime();
                oloaded = 0;
            };

            xhr.send(form);
        },
        insertHtml: function (v) {
            _this.ui.editor.execCommand("insertHtml", v);
        }
    };
    
	this.Config = {
        api:"http://localhost:8080/zyoffice/word/convert",
        word:"http://localhost:8080/zyoffice/word/convert",
        wordExport:"http://localhost:8080/zyoffice/word/export",
        pdf:"http://localhost:8080/zyoffice/pdf/upload"
    };

    if (arguments.length > 0) {
        var cfg = arguments[0];
        if (typeof (cfg) != "undefined") $.extend(true, this.Config, cfg);
        if (typeof (cfg.ui) != "undefined") $.extend(true, this.ui, cfg.ui);
    }

	this.LoadTo = function (o)
    {
        o.append('<input style="display: none" type="file" id="btnUpWord" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>\
        <input style="display: none" type="file" id="btnUpPdf" accept="application/pdf"/>\
<div id="w_dlg" style="display:none">\
            <img id = "w_ico" />\
                    <span id="w_msg"></div>\
</div>');
        this.ui.btn.up = $("#btnUpWord");
        this.ui.btn.pdf = $("#btnUpPdf");
        this.ui.btn.up.change(this.event.doc_sel);
        this.ui.btn.pdf.change(this.event.doc_sel);
        this.ui.dlg.panel = $("#w_dlg");
        this.ui.dlg.ico = $("#w_ico");
        this.ui.dlg.ico.attr("src", this.ui.ico.upload);
        this.ui.dlg.msg = $("#w_msg");
	};

	this.InsertHtml = function (html)
	{
	    _this.ui.editor.execCommand("insertHtml", html);
	};
	this.GetEditor = function () { return this.ui.editor; };

    //在FCKeditor_OnComplete()中调用
	this.SetEditor = function (edt)
	{
	    _this.ui.editor = edt;
        return this;
	};

    //init
    this.event.scriptReady();
}

var zyOffice = {
    instance: null,
    inited: false,
    getInstance: function (cfg) {
        if (this.instance == null) {
            this.instance = new zyOfficeManager(cfg);
            window.zyOffice = this.instance;
        }
        return this.instance;
    }
}